<template>
  <div class="product">
    <h2>产品列表页面</h2>
    <hr width="1900px" color="#808080" />
    <div class="cent">
      产品名称: <input type="text" value="请输入搜索关键字" />
      <router-link tag="button" to="/home/add">新增</router-link>
      <button>批量删除</button>
    </div>
    <table>
      <tr>
        <th><input type="checkbox" v-model="isCheckAll" /></th>
        <th>产品名称</th>
        <th>产品编号</th>
        <th>修改时间</th>
        <th>成本价</th>
        <th>库存数</th>
        <th>总价</th>
        <th>登记人</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in arr" :key="index">
        <td>
          <input type="checkbox" v-model="item.isCheck" />
        </td>
        <td>{{ item.pname }}</td>
        <td>{{ item.id }}</td>
        <td>{{ item.uptDate | times }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count }}</td>
        <td>{{ item.price * item.count }}</td>
        <td>{{ item.user }}</td>
        <td>
          <span>编辑</span> |
          <span @click="del(index)">删除</span>
        </td>
      </tr>
      <tr>
        <td colspan="9">合计: {{ arr.length }}类产品,总计: {{ total }}元。</td>
      </tr>
    </table>
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";
export default {
  computed: {
    ...mapState(["arr"]),
    isCheckAll: {
      get() {
        let flag = true;
        for (let i = 0; i < this.arr.length; i++) {
          if (this.arr[i].isCheck == false) {
            flag = false;
          }
        }
        return flag;
      },
      set(val) {
        this.arr.forEach((item) => (item.isCheck = val));
      },
    },
    total() {
      let sum = 0;
      sum = this.arr.reduce((total, curr) => {
        return total + (curr.isCheck ? curr.price * curr.count : 0);
      }, 0);
      return sum;
    },
  },
  created() {
    this.arr.forEach((item) => {
      this.$set(item, "isCheck", false);
    });
  },
  filters: {
    times: function (value) {
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let day = value.getDate();
      let hour = value.getHours();
      let min = value.getMinutes();
      return `${year}-${month}-${day} ${hour}:${min}`;
    },
  },
  methods: {
    ...mapMutations(["delProduct"]),
    del(idx) {
      this.delProduct(idx, 1);
    },
  },
};
</script>

<style lang="less" scoped>
h2 {
  margin: 20px 30px;
}
.cent {
  margin: 10px 10px;
  font-size: 18px;
  input {
    border: 2px solid #87ceeb;
    width: 250px;
    height: 45px;
    font-size: 18px;
    padding: 0 20px;
    color: #7b8288;
    outline: none;
  }
  button {
    background-color: #87ceeb;
    color: white;
    border: 0;
    padding: 12px 20px;
    font-size: 18px;
    margin-left: 10px;
    cursor: pointer;
  }
}
table {
  border-collapse: collapse;
  margin-left: 10px;
}
table td,
th {
  border: 1px solid black;
  padding: 10px 20px;
  text-align: center;
}
span {
  cursor: pointer;
}
</style>